package com.qf.controller;
/*
 *@Description:
 *@author:刘哥
 *@Date:19:41 2022/7/21
 * request.getParameter()方法只能获取name=value&name=value 这种类型请求参数
 * 但是该方法无法获取请求体中json的请求参数，使用jar包json解析方式将json请求数据转成java对象
 */


import com.alibaba.fastjson.JSON;
import com.qf.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * projectName:day14_vue_ajax
 * author:刘哥
 * time:2022/7/21 19:41
 * description:
 */
@WebServlet("/demo01")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
//        String username = request.getParameter("username");
//        System.out.println("username = " + username);
//        String password = request.getParameter("password");
//        String nickname = request.getParameter("nickname");
////        封装对象
//        User user = new User(username,password,nickname);
//        System.out.println("user = " + user);
//
////        将对象装换为json字符串
//        String json = JSON.toJSONString(user);
//
////        回写
//        response.getWriter().write(json);

//        post请求发送的是接收json数据
        User user= JSON.parseObject(request.getInputStream(), User.class);
        System.out.println("user = " + user);
        //将User对象转换为json字符串
        String json = JSON.toJSONString(user);
        response.getWriter().write(json);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
